import { capitalizePrint, addHeader } from './functions'
import Print from './print'

export default {
  print: (params, printFrame) => {
    // Check if we received proper data
    if (typeof params.printable !== 'object') {
      throw new Error('Invalid javascript data object (JSON).')
    }

    // Validate repeatTableHeader
    if (typeof params.repeatTableHeader !== 'boolean') {
      throw new Error('Invalid value for repeatTableHeader attribute (JSON).')
    }

    // Validate properties
    if (!params.properties || !Array.isArray(params.properties)) {
      throw new Error('Invalid properties array for your JSON data.')
    }

    // We will format the property objects to keep the JSON api compatible with older releases
    params.properties = params.properties.map(property => {
      return {
        field: typeof property === 'object' ? property.field : property,
        displayName: typeof property === 'object' ? property.displayName : property,
        columnSize: typeof property === 'object' && property.columnSize ? property.columnSize + ';' : 100 / params.properties.length + '%;',
        // 子数据
        sonProperties: property.sonProperties ? property.sonProperties : [],
        // 没有二级的数据
        columnNo: property.columnNo ? property.columnNo : false,
        col: property.col ? property.col : null
      }
    })

    // Create a print container element
    params.printableElement = document.createElement('div')

    // Check if we are adding a print header
    if (params.header) {
      addHeader(params.printableElement, params)
    }

    // Build the printable html data
    params.printableElement.innerHTML += jsonToHTML(params)

    // Print the json data
    Print.send(params, printFrame)
  }
}

function jsonToHTML(params) {
  // Get the row and column data
  const data = params.printable
  const properties = params.properties
  // 几级标题
  const headerRow = params.headerRow;

  // Create a html table
  let htmlData = '<table style="border-collapse: collapse; width: 100%;font-size:10px">'

  // Check if the header should be repeated
  if (params.repeatTableHeader) {
    htmlData += '<thead>'
  }

  // Add the table header row
  htmlData += '<tr>'

  // Add the table header columns
  if (headerRow == 1) {
    for (let a = 0; a < properties.length; a++) {
      htmlData += '<th style="width:' + properties[a].columnSize + ';' + params.gridHeaderStyle + '" >' + capitalizePrint(properties[a].displayName) + '</th>';
    }
    htmlData += '</tr>'
  } else if (headerRow == 2) {
    let { newHtmlData, sonProperties, length } = headerStr(properties, htmlData)
    htmlData += newHtmlData;
    htmlData += '<tr>'
    for (let a1 = 0; a1 < sonProperties.length; a1++) {
      sonProperties[a1].columnSize = sonProperties[a1].columnSize ? sonProperties[a1].columnSize + ';' : 100 / (sonProperties.length + length) + '%;';
      htmlData += '<th style="width:' + sonProperties[a1].columnSize + params.gridHeaderStyle + '" >' + capitalizePrint(sonProperties[a1].displayName) + '</th>';
    }
    htmlData += '</tr>'
  } else if (headerRow == 3) {
    let sonProperties = [];
    for (let a = 0; a < properties.length; a++) {
      let b = properties[a].sonProperties;
      if (b.length == 0) {
        htmlData += '<th style="width:' + properties[a].columnSize + ';' + params.gridHeaderStyle + '"' + `rowspan ="${headerRow}"` + ' >' + capitalizePrint(properties[a].displayName) + '</th>';
      } else {
        if (properties[a].col) {
          htmlData += '<th style="width:' + properties[a].columnSize + ';' + params.gridHeaderStyle + '"' + `colspan="${properties[a].col}"` + ' >' + capitalizePrint(properties[a].displayName) + '</th>';
        } else {
          htmlData += '<th style="width:' + properties[a].columnSize + ';' + params.gridHeaderStyle + '"' + `colspan="${b.length}"` + ' >' + capitalizePrint(properties[a].displayName) + '</th>';
        }
      }
      sonProperties.push(...properties[a].sonProperties);
    }
    htmlData += '</tr>'
    let Obj = headerStr(sonProperties, htmlData)
    let newHtmlDataTwo = Obj.newHtmlData;
    let sonPropertiesTwo = Obj.sonProperties;
    htmlData += newHtmlDataTwo;
    htmlData += '<tr>'
    for (let a1 = 0; a1 < sonPropertiesTwo.length; a1++) {
      htmlData += '<th style="width:' + properties[0].columnSize + ';' + params.gridHeaderStyle + '" >' + capitalizePrint(sonPropertiesTwo[a1].displayName) + '</th>';
    }
    htmlData += '</tr>'

    // {newHtmlDataTwo:newHtmlData, sonPropertiesTwo:sonProperties}
  }

  // 获取表头
  function headerStr(properties, htmlData) {
    // headerRow级要渲染的数据
    let sonProperties = [];
    let length = 0;
    for (let a = 0; a < properties.length; a++) {
      let b = properties[a].sonProperties;
      if (properties[a].columnNo) {
        length++;
      }
      if (b.length == 0) {
        htmlData += '<th style="width:' + properties[a].columnSize + params.gridHeaderStyle + '"' + `rowspan ="${headerRow}"` + ' >' + capitalizePrint(properties[a].displayName) + '</th>';
      } else {
        htmlData += '<th style="width:' + properties[a].columnSize + params.gridHeaderStyle + '"' + `colspan="${b.length}"` + ' >' + capitalizePrint(properties[a].displayName) + '</th>';
      }
      sonProperties.push(...properties[a].sonProperties);
    }
    htmlData += '</tr>'
    return { newHtmlData: htmlData, sonProperties, length }
  }



  // Add the closing tag for the table header row

  // If the table header is marked as repeated, add the closing tag
  if (params.repeatTableHeader) {
    htmlData += '</thead>'
  }

  // Create the table body
  htmlData += '<tbody>'

  // 合并第几行
  const listRow = params.listRow;
  // 合并多少列
  const colSpan = params.colSpan;
  // Add the table data rows
  for (let i = 0; i < data.length; i++) {
    // Add the row starting tag
    htmlData += '<tr>'
    let arrTd = [];
    if (headerRow == 1) {
      arrTd = properties;
    } else if (headerRow == 2) {
      properties.map(item => {
        if (item.sonProperties.length == 0) {
          arrTd.push({ ...item })
        } else {
          arrTd.push(...item.sonProperties)
        }
      })
    }
    // 每个单元格的数据
    // Print selected properties only
    for (let n = 0; n < arrTd.length; n++) {
      let stringData = data[i]
      // Support nested objects
      const property = arrTd[n].field.split('.')
      if (property.length > 1) {
        for (let p = 0; p < property.length; p++) {
          stringData = stringData[property[p]]
        }
      } else {
        stringData = stringData[arrTd[n].field]
      }
      // 因为后台数据有些有null值，所以统一转化为''
      stringData = stringData == null ? "" : stringData;
      // 是否开启合并，合计行
      if (listRow && i + 1 == listRow) {
        if (n == 0) {
          htmlData += '<td style="width:' + arrTd[n].columnSize + params.gridStyle + '" ' + `colspan ="${colSpan}"` + '>' + stringData + '</td>'
        } else if (n >= colSpan) {
          // Add the row contents and styles
          htmlData += '<td style="width:' + arrTd[n].columnSize + params.gridStyle + '">' + stringData + '</td>'
        }
      } else {
        // Add the row contents and styles
        htmlData += '<td style="width:' + arrTd[n].columnSize + params.gridStyle + '">' + stringData + '</td>'
      }
    }

    // Add the row closing tag
    htmlData += '</tr>'
  }

  // Add the table and body closing tags
  htmlData += '</tbody></table>'
  // 页尾数据
  const endPage = params.endPage;
  htmlData += endPage;
  return htmlData;

}
